﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using JobDescOnline.Presentation.Models;
using eq.CoreBase.View;
using eq.CoreBase.Control;

namespace JobDescOnline.Presentation.Controllers
{
    public class RoleController : Controller
    {
        //
        // GET: /Role/
        public JobDescDBEntities1 db = new JobDescDBEntities1();

        public ActionResult Index()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            int total = 0;
            
            var model = Roless.RetrieveByFilterAndPage(page, pagesize, sort, direction);
            total = Roless.RetrieveByFilter();

            ViewData["Dir"] = direction.ToLower() == "asc" ? "desc" : "asc";

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Roles/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();
            return View(model);
        }

        public ActionResult AjaxTable()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            string sort = !string.IsNullOrEmpty(Request.QueryString["sort"]) ? Request.QueryString["sort"] : "ID";
            string direction = !string.IsNullOrEmpty(Request.QueryString["direction"]) ? Request.QueryString["direction"] : "ASC";

            dynamic model = null;
            int total = 0;

            if (filters.Count > 0)
            {
                model = Roless.RetrieveByFilterAndPage(filters, page, pagesize, sort, direction);
                total = Roless.RetrieveByFilter(filters);
            }
            else
            {
                model = Competencies.RetrieveByFilterAndPage(page, pagesize, sort, direction);
                total = Competencies.RetrieveByFilter();
            }

            if (total > 0) return View(model);
            else return View("Empty");
        }

        public ActionResult AjaxPaging()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            int total = 0;

            if (filters.Count > 0)
            {
                total = Roless.RetrieveByFilter(filters);
            }
            else
            {
                total = Roless.RetrieveByFilter();
            }

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Roles/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();

            return View();
        }

        //
        // GET: /Role/Create

        public ActionResult Create()
        {
            RolePrivilege model = new RolePrivilege();
            model.Role = new Role();
            model.PrivilegeMenu = Privileges.RetrieveByRoleID();
            return View(model);
        } 

        //
        // POST: /Role/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    Role role = db.Roles.CreateObject();
                    role.Rowstatus = Convert.ToBoolean(collection["Role.Rowstatus"]);
                    role.RoleName = collection["Role.RoleName"];
                    role.Description = collection["Role.Description"];
                    role.CreatedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    role.CreatedOn = DateTime.Now;

                    db.Roles.AddObject(role);
                    Privileges.UpdatePrivilege(role.ID, collection, db);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Role/Edit/5
 
        public ActionResult Edit(int id)
        {
            RolePrivilege model = new RolePrivilege();
            model.Role = db.Roles.Single(r => r.ID == id); ;
            model.PrivilegeMenu = Privileges.RetrieveByRoleID(id);
            return View(model);
        }

        //
        // POST: /Role/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    Role role = db.Roles.First(r => r.ID == id);
                    role.Rowstatus = Convert.ToBoolean(collection["Role.Rowstatus"]);
                    role.RoleName = collection["Role.RoleName"];
                    role.Description = collection["Role.Description"];
                    role.LastModifiedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    role.LastModifiedOn = DateTime.Now;

                    db.Roles.ApplyCurrentValues(role);
                    Privileges.UpdatePrivilege(id, collection, db);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Edit/" + id.ToString());
            }
        }

        //
        // POST: /Role/Delete/5
        
        public ActionResult Delete(int id)
        {
            Role role = db.Roles.Single(r => r.ID == id);
            var privilieges = db.Privilleges.Where(p => p.RoleID == id);
            foreach (var privilege in privilieges)
            {
                db.Privilleges.DeleteObject(privilege);
            }

            db.Roles.DeleteObject(role);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
